package com.leenmvc.core.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Locale;

/**
 * des加密工具
 */
public class DesUtils {

    private static final String DES_ALGORITHM = "DES";

    /**
     * 加密/解密算法-工作模式-填充模式
     */
    private static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";

    /**
     * 默认编码
     */
    private static final String CHARSET = "utf-8";

//    /**
//     * DES解密
//     *
//     * @param secretData 密码字符串
//     * @param secretKey  解密密钥
//     * @return 原始字符串
//     * @throws Exception
//     */
//    public static String decryption(String secretData, String secretKey) throws Exception {
//        Cipher cipher = null;
//        try {
////            cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
//            cipher = Cipher.getInstance(CIPHER_ALGORITHM);
//            cipher.init(Cipher.DECRYPT_MODE, generateKey(secretKey));
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//            throw new Exception("NoSuchAlgorithmException", e);
//        } catch (NoSuchPaddingException e) {
//            e.printStackTrace();
//            throw new Exception("NoSuchPaddingException", e);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        try {
//
//            byte[] buf = cipher.doFinal(hexStr2Bytes(secretData));
//            int num = 0;
//            for (byte b : buf) {
//                String name = b + "";
//                if (name.length() == 1) {
//                    num++;
//                }
//            }
//
//            byte[] bytes = new byte[buf.length - num];
//            for (int i = 0; i < buf.length; i++) {
//                String name = buf[i] + "";
//                if (name.length() != 1) {
//                    bytes[i] = buf[i];
//                }
//            }
//
//            return new String(bytes, "utf-8");
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new Exception("IllegalBlockSizeException", e);
//        }
//    }

    public static byte[] hexStr2Bytes(String src) {
        /*对输入值进行规范化整理*/
        src = src.trim().replace(" ", "").toUpperCase(Locale.US);
        //处理值初始化
        int m = 0, n = 0;
        int iLen = src.length() / 2; //计算长度
        byte[] ret = new byte[iLen]; //分配存储空间

        for (int i = 0; i < iLen; i++) {
            m = i * 2 + 1;
            n = m + 1;
            ret[i] = (byte) (Integer.decode("0X" + src.substring(i * 2, m) + src.substring(m, n)) & 0xFF);
        }
        return ret;
    }

    /**
     * 获得秘密密钥
     *
     * @param secretKey
     * @return
     * @throws NoSuchAlgorithmException
     */
    private static SecretKey generateKey(String secretKey)
            throws Exception {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM);
        DESKeySpec keySpec = new DESKeySpec(secretKey.getBytes());
        return keyFactory.generateSecret(keySpec);
    }

    /**
     * DES加密操作
     * @param source 要加密的源
     * @param key    约定的密钥
     * @return
     */
    public static String encryptDES(String source,String key){
        //强加密随机数生成器
//        SecureRandom random = new SecureRandom();
        try {
            //创建密钥规则
//            DESKeySpec keySpec = new DESKeySpec(key.getBytes());
            //创建密钥工厂
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            //按照密钥规则生成密钥
//            SecretKey secretKey =  keyFactory.generateSecret(keySpec);
            //加密对象
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            //初始化加密对象需要的属性
            cipher.init(Cipher.ENCRYPT_MODE, generateKey(key));
            //开始加密
            byte[] result = cipher.doFinal(source.getBytes(CHARSET));
            //Base64加密
            return  new String(Base64.getEncoder().encode(result),CHARSET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     * @param cryptograph 密文
     * @param key         约定的密钥
     * @return
     */
    public static String decryptDES(String cryptograph,String key){
        //强加密随机生成器
        SecureRandom random  =  new SecureRandom();
        try {
            //定义私钥规则
//            DESKeySpec keySpec = new DESKeySpec(key.getBytes());
            //定义密钥工厂
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
            //按照密钥规则生成密钥
//            SecretKey secretkey = factory.generateSecret(keySpec);
            //创建加密对象
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, generateKey(key), random);
            //Base64对
            byte[] result = Base64.getDecoder().decode(cryptograph);
            return new String(cipher.doFinal(result),CHARSET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
